package com.nrgedge.magnolia.action;


import info.magnolia.jcr.util.NodeTypes;
import info.magnolia.jcr.util.PropertyUtil;
import info.magnolia.ui.admincentral.dialog.action.SaveDialogAction;
import info.magnolia.ui.api.action.ActionExecutionException;
import info.magnolia.ui.form.EditorCallback;
import info.magnolia.ui.form.EditorValidator;
import info.magnolia.ui.vaadin.integration.jcr.JcrNodeAdapter;

import javax.jcr.Node;
import javax.jcr.Property;
import javax.jcr.PropertyIterator;
import javax.jcr.PropertyType;
import javax.jcr.RepositoryException;

import com.vaadin.data.Item;

public class EscapeMustacheSaveAction extends SaveDialogAction {

    public EscapeMustacheSaveAction(EscapeMustacheSaveActionDefinition definition, Item item, EditorValidator validator, EditorCallback callback) {
        super(definition, item, validator, callback);
    }

    @Override
    public void execute() throws ActionExecutionException {
        // First Validate
        validator.showValidation(true);
        if (validator.isValid()) {
            final JcrNodeAdapter itemChanged = (JcrNodeAdapter) item;
            try {
                final Node node = itemChanged.applyChanges();

                PropertyIterator properties = node.getProperties();
                
                while(properties.hasNext()) {
                	Property property = properties.nextProperty();
                	
                	if (property.getType() == PropertyType.STRING) {
                		String value = property.getString();
                		if (value != null) {
                			if (value.contains("{{") || value.contains("}}")) {
                				value = value.replace("{{", "&#123;&#123;");
                				value = value.replace("}}", "&#125;&#125;");
                				
                				PropertyUtil.setProperty(node, property.getName(), value);
                			}
                			
                		}
                	}
                }

                NodeTypes.LastModified.update(node);
                node.getSession().save();
            } catch (final RepositoryException e) {
                throw new ActionExecutionException(e);
            }
            callback.onSuccess(getDefinition().getName());
        }
    }
}
